package com.study.ju.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.study.ju.enums.RespCode;
import com.study.ju.model.res.ActionResponse;
import com.study.ju.web.AopTestController;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

/**
 * <p>form表单提交校验token</p>
 *
 * @author chentao
 * @version v 0.1 2023/5/29 13:45
 */
public class FormSubmitTokenInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(FormSubmitTokenInterceptor.class);

    private String formSubmitTokenInterceptorUrls = "[\"/testJson\",\"/test/testJson\",\"/test/testWwwFrom\",\"/test/testRequestParam\"]";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = getRequestURI(request);
        if ("POST".equals(request.getMethod().toUpperCase()) && StringUtils.isNotEmpty(formSubmitTokenInterceptorUrls)) {
            List<String> formInterceptorUrls = JSONArray.parseArray(formSubmitTokenInterceptorUrls, String.class);
            if (CollectionUtils.isNotEmpty(formInterceptorUrls)) {
                boolean contains = formInterceptorUrls.stream().anyMatch(e -> e.contains(requestURI));
                if (contains) {
                    String formToken = null;
                    String contentType = request.getContentType();
                    System.out.println(contentType);
                    if ("application/json".equalsIgnoreCase(contentType)) {
                        ResettableServletRequestWrapper resettableServletRequestWrapper = new ResettableServletRequestWrapper(request);
                        String bodyParam = IOUtils.toString(resettableServletRequestWrapper.getInputStream());
                        System.out.println(bodyParam);
                        if (StringUtils.isNotEmpty(bodyParam)) {
                            JSONObject jsonObject = JSONObject.parseObject(bodyParam);
                            if (jsonObject.containsKey("formToken")) {
                                formToken = (String) jsonObject.get("formToken");
                                System.out.println("formToken:" + formToken);
                            }
                        }

                    } else {
                        if (StringUtils.isNotEmpty(request.getParameter("formToken"))) {
                            formToken = request.getParameter("formToken");
                            System.out.println("formToken2:" + request.getParameter("formToken"));
                        }
                        System.out.println("name:" + request.getParameter("name"));
                    }
                    if (!"222".equals(formToken)) {
                        responseWithJson(response,JSON.toJSONString(ActionResponse.of(RespCode._C400, "token错误")));
                        return false;
                    }

                }

            }
        }
        return true;
    }

    /**
     * 直接给前端返回json格式数据
     */
    protected void responseWithJson(HttpServletResponse response, String json) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(json);
        } catch (IOException e) {
            logger.error("执行responseWithJson异常：", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    /**
     * 获取用户请求的path，不带contextPath
     * 如：/index.htm
     */
    public static String getRequestURI(HttpServletRequest request) {
        return StringUtils.replace(request.getRequestURI(), request.getContextPath(), "");
    }
}
